<template>
  <div class="file-storage">
    <div class="storage-header">
      <div class="storage-info">
        <el-icon><Folder /></el-icon>
        <span class="title">文件存储管理</span>
        <el-tag type="info" size="small">{{ formatFileSize(totalSize) }} / {{ formatFileSize(maxSize) }}</el-tag>
      </div>
      <div class="storage-actions">
        <el-button type="primary" size="small" @click="handleUpload">
          <el-icon><Upload /></el-icon>
          上传文件
        </el-button>
        <el-button size="small" @click="handleCreateFolder">
          <el-icon><FolderAdd /></el-icon>
          新建文件夹
        </el-button>
      </div>
    </div>

    <div class="storage-content">
      <!-- 左侧目录树 -->
      <div class="directory-tree">
        <div class="tree-header">
          <span>目录结构</span>
        </div>
        <el-tree
          :data="directoryTree"
          :props="treeProps"
          @node-click="handleNodeClick"
          :highlight-current="true"
          :expand-on-click-node="false"
          class="folder-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <el-icon><FolderOpened v-if="data.isOpen" /><Folder v-else /></el-icon>
              <span class="node-label">{{ node.label }}</span>
              <span class="node-count" v-if="data.children">({{ data.children.length }})</span>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 右侧文件列表 -->
      <div class="file-list">
        <div class="list-header">
          <div class="breadcrumb">
            <span>{{ currentPath || '存储空间' }}</span>
          </div>
          <div class="list-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索文件..."
              size="small"
              style="width: 200px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <div class="file-table">
          <el-table
            :data="filteredFiles"
            style="width: 100%"
            @row-click="handleRowClick"
            :show-header="false"
          >
            <el-table-column width="50">
              <template #default="{ row }">
                <el-icon size="20" :style="{ color: row.type === 'folder' ? '#409eff' : '#67c23a' }">
                  <Folder v-if="row.type === 'folder'" />
                  <Document v-else />
                </el-icon>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="文件名">
              <template #default="{ row }">
                <div class="file-name">
                  <span>{{ row.name }}</span>
                  <el-tag v-if="row.type === 'folder'" size="small" type="info">{{ row.count }}项</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" width="120">
              <template #default="{ row }">
                <span v-if="row.type !== 'folder'">{{ formatFileSize(row.size) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="modified" label="修改时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.modified) }}
              </template>
            </el-table-column>
            <el-table-column width="120">
              <template #default="{ row }">
                <div class="file-actions">
                  <el-button type="text" size="small" @click.stop="handleDownload(row)">
                    <el-icon><Download /></el-icon>
                  </el-button>
                  <el-button type="text" size="small" @click.stop="handleDelete(row)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!filteredFiles.length"
          description="暂无文件"
          :image-size="100"
        />
      </div>
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        multiple
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传各种格式的视频、音频、图片文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 图标
import {
  Folder,
  FolderOpened,
  FolderAdd,
  Upload,
  Download,
  Delete,
  Search,
  Document
} from '@element-plus/icons-vue'

// 状态变量
const currentPath = ref('')
const searchKeyword = ref('')
const uploadDialogVisible = ref(false)
const uploadUrl = '/api/upload'

// 存储信息
const totalSize = ref(1024 * 1024 * 500) // 500MB
const maxSize = ref(1024 * 1024 * 1024 * 5) // 5GB

// 目录树数据
const directoryTree = ref([
  {
    id: 1,
    label: '存储空间',
    path: '/',
    isOpen: true,
    children: [
      {
        id: 2,
        label: '直播录像',
        path: '/recordings',
        children: [
          { id: 3, label: '2024年', path: '/recordings/2024' },
          { id: 4, label: '2023年', path: '/recordings/2023' }
        ]
      },
      {
        id: 5,
        label: '拆条素材',
        path: '/clips',
        children: [
          { id: 6, label: '精彩片段', path: '/clips/highlights' },
          { id: 7, label: '广告素材', path: '/clips/ads' }
        ]
      },
      {
        id: 8,
        label: '备份文件',
        path: '/backup'
      }
    ]
  }
])

// 文件列表数据
const files = ref([
  {
    id: 1,
    name: '直播录像20240101.mp4',
    type: 'file',
    size: 1024 * 1024 * 120,
    modified: new Date('2024-01-01'),
    path: '/recordings/2024'
  },
  {
    id: 2,
    name: '精彩片段合集',
    type: 'folder',
    count: 15,
    modified: new Date('2024-01-15'),
    path: '/clips/highlights'
  },
  {
    id: 3,
    name: '广告素材包.zip',
    type: 'file',
    size: 1024 * 1024 * 45,
    modified: new Date('2024-01-10'),
    path: '/clips/ads'
  }
])

// 树形配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 计算属性
const filteredFiles = computed(() => {
  let result = files.value
  
  // 按当前路径过滤
  if (currentPath.value) {
    result = result.filter(file => file.path === currentPath.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    result = result.filter(file => 
      file.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  return result
})

// 方法
const handleNodeClick = (data) => {
  currentPath.value = data.path
}

const handleRowClick = (row) => {
  if (row.type === 'folder') {
    currentPath.value = row.path
  }
}

const handleUpload = () => {
  uploadDialogVisible.value = true
}

const handleCreateFolder = () => {
  ElMessageBox.prompt('请输入文件夹名称', '新建文件夹', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[^\\/:*?"<>|]+$/,
    inputErrorMessage: '文件夹名称不能包含特殊字符'
  }).then(({ value }) => {
    const newFolder = {
      id: Date.now(),
      name: value,
      type: 'folder',
      count: 0,
      modified: new Date(),
      path: currentPath.value || '/'
    }
    files.value.push(newFolder)
    ElMessage.success('文件夹创建成功')
  })
}

const handleDownload = (file) => {
  if (file.type === 'file') {
    ElMessage.success(`开始下载：${file.name}`)
    // 实际项目中这里会触发下载API
  } else {
    ElMessage.info('文件夹暂不支持下载')
  }
}

const handleDelete = (file) => {
  ElMessageBox.confirm(
    `确定要删除 ${file.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = files.value.findIndex(f => f.id === file.id)
    if (index > -1) {
      files.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

const handleUploadSuccess = () => {
  ElMessage.success('上传成功')
  uploadDialogVisible.value = false
  // 刷新文件列表
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 工具函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

onMounted(() => {
  // 这里可以加载实际的文件数据
})
</script>

<style scoped>
.file-storage {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  margin: 0;
  padding: 0;
}

.storage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
  height: 60px;
  box-sizing: border-box;
}

.storage-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.storage-info .title {
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
}

.storage-actions {
  display: flex;
  gap: 10px;
}

.storage-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  height: calc(100% - 60px);
}

/* 左侧目录树 - 关键优化 */
.directory-tree {
  width: 250px;
  min-width: 200px;
  max-width: 300px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tree-header {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #2c3e50;
  flex-shrink: 0;
  background: #fafafa;
}

.folder-tree {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 15px;
  font-size: 14px;
  transition: background-color 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
}

.tree-node:hover {
  background-color: #f5f7fa;
}

:deep(.el-tree-node__content) {
  height: 36px;
  padding: 0 15px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.node-count {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

/* 右侧文件列表 */
.file-list {
  flex: 1;
  background: white;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
  flex-shrink: 0;
}

.breadcrumb {
  font-size: 14px;
  color: #606266;
}

.file-table {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-actions {
  display: flex;
  gap: 5px;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
}

:deep(.el-table__row:hover) {
  cursor: pointer;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}

/* 响应式设计 - 确保在小屏幕上正常显示 */
@media screen and (max-width: 768px) {
  .directory-tree {
    width: 200px;
    min-width: 180px;
  }
  
  .storage-header {
    padding: 10px 15px;
  }
  
  .storage-actions {
    gap: 5px;
  }
}

@media screen and (max-width: 480px) {
  .directory-tree {
    width: 150px;
    min-width: 150px;
  }
  
  .storage-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    height: auto;
  }
  
  .storage-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>